import axios from 'axios'
import store from '@/vuex/store.js'
import router from '../router'
let qs = require('qs')

let baseURL = '/api/index.php'// 真实地址
// axios.defaults.baseURL = baseURL // 模拟地址
axios.defaults.timeout = 10000
axios.defaults.withCredentials = true
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 用户鉴权
axios.interceptors.response.use(function (response) {
    return response
  }, function (error) {
    // 对响应错误做点什么
    store.commit('SET_LOADING',false);

    if(errore.response) {

      if(error.response.status== 401) { // 这个暂时还没有和后端确认到时候可以确认一个统一的code
          // 如果返回401 即没有权限，跳到登录页重新登录
        store.commit('CHANGE_TOKEN',0);

        alert('请重新登录');

        router.replace({
          path: 'login',
          query: {redirect: router.currentRoute.fullPath}
        })

      }
    }

    return Promise.reject(error);
  });
let api = axios
// axios 二次封装
export default {
  fetchGet (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.get(`${baseURL}${url}`, {
        params: params
      }).then(res => {
        resolve(res.data)
      })
    })
  },
  fetchPost (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(`${baseURL}${url}`, qs.stringify(params)).then(res => {
        resolve(res.data)
      })
    })
  },
  api
}
